package com.beta.resource.utils;

import com.alibaba.fastjson.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;


public class Security {

    public static Boolean verfiyOAuthToken(String url, String clientid, String clientsecret, String username, String token){
        Boolean ret = null;
        OutputStreamWriter out = null;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();
        try{
            URL introspectUrl = new URL(url);
            HttpURLConnection conn =(HttpURLConnection)introspectUrl.openConnection();
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
            "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.connect();
            out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            String data = String.format("username=%s&client_id=%s&client_secret=%s&token=%s", username, clientid, clientsecret, token);
            out.write(data);
            out.flush();
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            System.out.println(String.format("verfiyOAuthToken: params(%s),", data, result.toString()));
            ret = JSONObject.parseObject(result.toString()).getBoolean("active");
        }catch(IOException e){
            e.printStackTrace();
        }finally{
            try{
                if(out != null){
                    out.close();
                }
                if(in != null){
                    in.close();
                }
            }catch(IOException e){
                e.printStackTrace();
            }
        }
        System.out.println("verfiyOAuthToken ret:" + ret);
        return ret;
    }
}
